package com.twl.app.base.util;

import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.aspectj.weaver.patterns.ThisOrTargetAnnotationPointcut;
import org.springframework.stereotype.Service;

import com.twl.app.base.entity.Checktemplet;
import com.twl.app.base.entity.Uemp;

/**
 * <p>日期模式工具类</p>
 * @author llxia
 * @version 1.0
 * */
@Service("DateComm")
public class DateComm {
	
	
	/**
	 * 得到发薪期间
	 * @return
	 */
	public static String getDateMoney(Uemp uemp , Checktemplet checktemplet){
		if("0".equals(uemp.getStafftype())){//正式
			return DateComm.getNextYearMonth(checktemplet.getPeriod());
		}else{//派遣
			return checktemplet.getPeriod();
		}
	}
	
	/**
	 * date(yyyyMM) to 下个月（yyyy/MM/dd）
	 * @param date
	 * @return
	 */
	public static Date getRealDate(String date){
		SimpleDateFormat df = new SimpleDateFormat("yyyyMM");//设置日期格式
		Date periodDate = null;
		try {
			periodDate = df.parse(date);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		Calendar c = Calendar.getInstance();
		c.setTime(periodDate);
		c.add(Calendar.MONTH, 1);
		
	    return c.getTime() ;
		
	}
	/**
	 * 得到输入日期下个月的年月（yyyyMM）
	 * @param period (yyyyMM)
	 * @return
	 */
	public static String getNextYearMonth(String period){
		SimpleDateFormat df = new SimpleDateFormat("yyyyMM");//设置日期格式
		Date periodDate = null;
		try {
			periodDate = df.parse(period);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		Calendar c = Calendar.getInstance();
		c.setTime(periodDate);
		c.add(Calendar.MONTH, 1);
		
	    return new SimpleDateFormat("yyyyMM").format(c.getTime()) ;

	}
	
	/**
	 * 把日期yyyyMMdd转成yyyy/MM/dd
	 * @return
	 * @throws ParseException 
	 */
	public static String getFormatStr(String dateStr){
		SimpleDateFormat s1 = new SimpleDateFormat("yyyyMMdd") ;
		SimpleDateFormat s2 = new SimpleDateFormat("yyyy/MM/dd");
		try {
			Date date = s1.parse(dateStr);
			String da = s2.format(date);
			return da ;
		} catch (ParseException e) {
			e.printStackTrace();
			return "format failed" ;
		}
		
		
	}
	/**
	 * 得到当前日期上个月的年月（yyyyMM）
	 * @return
	 */
	public static String getLastYearMonth(){
		 Calendar c = Calendar.getInstance();
	     c.add(Calendar.MONTH, -1);
	     
	     return new SimpleDateFormat("yyyyMM").format(c.getTime()) ;
	}
	/**
	 * 两个日期（yyyy/MM/dd）相隔几个月
	 * @param startStr
	 * @param endStr
	 * @return
	 */
	public static int getMonth(String startStr, String endStr) {
		SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");//设置日期格式
		 Date start = null;
		 Date end = null  ;
		try {
			start = df.parse(startStr);
		    end = df.parse(endStr);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		
        if (start.after(end)) {
            Date t = start;
            start = end;
            end = t;
        }
        Calendar startCalendar = Calendar.getInstance();
        startCalendar.setTime(start);
        Calendar endCalendar = Calendar.getInstance();
        endCalendar.setTime(end);
        Calendar temp = Calendar.getInstance();
        temp.setTime(end);
        temp.add(Calendar.DATE, 1);
 
        int year = endCalendar.get(Calendar.YEAR)
                - startCalendar.get(Calendar.YEAR);
        int month = endCalendar.get(Calendar.MONTH)
                - startCalendar.get(Calendar.MONTH);
 
        if ((startCalendar.get(Calendar.DATE) == 1)
                && (temp.get(Calendar.DATE) == 1)) {
            return year * 12 + month + 1;
        } else if ((startCalendar.get(Calendar.DATE) != 1)
                && (temp.get(Calendar.DATE) == 1)) {
            return year * 12 + month;
        } else if ((startCalendar.get(Calendar.DATE) == 1)
                && (temp.get(Calendar.DATE) != 1)) {
            return year * 12 + month;
        } else {
            return (year * 12 + month - 1) < 0 ? 0 : (year * 12 + month);
        }
    }
	
	
	/**
	 * 获取日期字符串，格式yyyyMM
	 * @return
	 */
	public static String getDateNow(){
		String date = new SimpleDateFormat("yyyyMM").format(new Date());
		
		return date ;
	}
	/**
	 * 得到与当前时间的月份差(整月)
	 * @param rzDate
	 * @return
	 */
	public static Integer calDate(Checktemplet checktemplet,String rzDate){
		//FIXME
		String nowMonth = new SimpleDateFormat("MM").format(getRealDate(checktemplet.getPeriod()));
		String nowDate = null;
		if(nowMonth.equals("01")){
			nowDate = new StringBuffer(String.valueOf(Calendar.getInstance().get(Calendar.YEAR))).append("0105").toString();
		}else if(nowMonth.equals("07")){
			nowDate = new StringBuffer(String.valueOf(Calendar.getInstance().get(Calendar.YEAR))).append("0705").toString();
		}
		Integer month = null;
		try {
			Calendar now = Calendar.getInstance();
			now.setTime(new SimpleDateFormat("yyyyMMdd").parse(nowDate));
			Calendar rz = Calendar.getInstance();
			now.setTime(new SimpleDateFormat("yyyyMMdd").parse(rzDate));
			long time = now.getTimeInMillis()-rz.getTimeInMillis();
			month = (int) (time/1000/60/60/24/30);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		   return month;
	}
	
	/**
	 * 比较月份差*(相差两个月)
	 * @return
	 */
	public static boolean checkDate(String date) throws ParseException {
		Calendar c = Calendar.getInstance();
		c.add(c.MONTH,-1);
		Date nowDate = c.getTime();
		String nowTime =new SimpleDateFormat("yyyyMM").format(nowDate); 
		if(nowTime.equals(date.substring(0,6))){
			return true ;
		}else{
			return false ;
		}
	}
	/**
	 * 在职年限
	 * @param date
	 * @return
	 */
	public static double compareTime(String date,Checktemplet checktemplet){
		double year =0;
		try {
			Calendar nowDate = Calendar.getInstance();
			//FIXME
			nowDate.setTime(getRealDate(checktemplet.getPeriod()));
			Calendar d = Calendar.getInstance();
			d.setTime(new SimpleDateFormat("yyyyMMdd").parse(date));
			double val = nowDate.getTimeInMillis()-d.getTimeInMillis();
			 year = val/1000/60/60/24/365 ;
			
		} catch (Exception e) {
			
		}
		return year ;
	}
	/**
	 * <p>Date to yyyy/MM/dd</p>
	 * @param date
	 * @return
	 */
	public static String dateFormatToStr(Date date){
		if(date ==null){
			return "";
		}
		return (new SimpleDateFormat("yyyy/MM/dd")).format(date);
	}
	/**
	 * <p>Date to yyyyMMdd</p>
	 * */
	public static String dateFormatToStr1(Date date){
		if(date ==null){
			return "";
		}
		return (new SimpleDateFormat("yyyyMMdd")).format(date);
	}
	/**
	 * <p>yyyyMMdd to Date</p>
	 * */	
	public static Date strFormatToDate1(String dateStr){
		Date date=null;
		try {
			date=(new SimpleDateFormat("yyyyMMdd")).parse(dateStr);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return date;
	}
	/**
	 * <p>Date to yyyyMM</p>
	 **/	
	public static String dateFormatToStr2(Date date){
		if(date ==null){
			return "";
		}
		return (new SimpleDateFormat("yyyyMM")).format(date);
	}
	/**
	 * <p>yyyyMM to Date</p>
	 * */	
	public static Date strFormatToDate2(String dateStr){
		Date date=null;
		try {
			date=(new SimpleDateFormat("yyyyMM")).parse(dateStr);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return date;
	}
	/**
	 * <p>Date to yyyy-MM-dd</p>
	 * */	
	public static String dateFormatToStr3(Date date){
		if(date == null){
			return "";
		}
		return (new SimpleDateFormat("yyyy-MM-dd")).format(date);
	}
	/**
	 * <p>yyyy-MM-dd to Date</p>
	 * */		
	public static Date strFormatToDate3(String dateStr){
		Date date=null;
		try {
			date=(new SimpleDateFormat("yyyy-MM-dd")).parse(dateStr);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return date;
	}
	/**
	 * <p>Date to yyyy-MM</p>
	 * */	
	public static String dateFormatToStr4(Date date){
		return (new SimpleDateFormat("yyyy-MM")).format(date);
	}
	/**
	 * <p>Date to yyyy.MM</p>
	 * */	
	public static String dateFormatToStr5(Date date){
		return (new SimpleDateFormat("yyyy.MM")).format(date);
	}
	
	
	/**
	 * <p>yyyy-MM to Date</p>
	 * */	
	public static Date strFormatToDate4(String dateStr){
		Date date=null;
		try {
			date=(new SimpleDateFormat("yyyy-MM")).parse(dateStr);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return date;
	}	
	
	
	/**
	 * 
	 * @param fbjbxx
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static List toList(Object[] array){
		List list = new ArrayList();
		int i ;
		int len = array.length;
		for(i = 0 ; i < len ; i++){
			list.add(array[i]);
		}
		return list;
	}
	
	public static String charChang(String str){
		String tempStr=null;
		if(str!=null){
			try {
				tempStr=new String(str.getBytes("iso8859-1"),"GBK");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		return tempStr;
	}	
	
	/**
	 * 获取当前时间前12个月的时间
	 * @return
	 */
	public static Date getLast12Month(){
		Calendar c = Calendar.getInstance();
		c.add(Calendar.MONTH, -12);
		return c.getTime();
	}
	
	/**
	 * 获取当前时间前1个月的时间
	 * @return
	 */
	public static Date getLastMonth(){
		Calendar c = Calendar.getInstance();
		c.add(Calendar.MONTH, -1);
		return c.getTime();
	}
	
	/**
	 * 从当前时间往前30的日期
	 * @return
	 */
	public static Date getLast30Days(){
		Calendar c = Calendar.getInstance();
		c.add(Calendar.DAY_OF_YEAR, -30);
		return c.getTime();
	}
	/**
	 *  从当前时间往前三个月日期
	 * @return
	 */
	public static Date getLastThreeMonth(){
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.MONTH, -3);
	    return calendar.getTime();
	}
//	public static void main(String[] args){
//		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
//		System.out.println(sdf.format(getLast12Month()));
//		System.out.println(sdf.format(getLastMonth()));
//		System.out.println(sdf.format(getLast30Days()));
//	}
	
	/**
	 * 得到yyyyMMddHHmmss格式的日期
	 * @param date
	 * @return
	 */
	public static String dateFormatToStr6(Date date){
		if(date ==null){
			return "";
		}
		return (new SimpleDateFormat("yyyyMMddHHmmss")).format(date);
	}
	
	/**
	 * 得到参数日期往前推一个月的日期
	 * @param date
	 * @return dateStr 'yyyy-MM-dd'
	 */
	public static String getLastMonthDay(Date date){
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		c.add(Calendar.MONDAY, -1);
		c.add(Calendar.DATE,1);
		String returnDate=dateFormatToStr3(c.getTime());
		return returnDate;
	}
	
	/**
	 * <p>Date to yyyy年MM月</p>
	 * */	
	public static String dateFormatToStr7(Date date){
		return (new SimpleDateFormat("yyyy年MM月")).format(date);
	}
	/**
	 * <p>Date to yyyy年MM月dd日</p>
	 * */	
	public static String dateFormatToStr8(Date date){
		return (new SimpleDateFormat("yyyy年MM月dd日")).format(date);
	}
	/**
	 * <p>yyyy/MM/dd to Date</p>
	 * 	@return yyyy/MM/dd
	 * */	
	public static Date strFormatToDate5(String dateStr){
		Date date=null;
		try {
			date=(new SimpleDateFormat("yyyy/MM/dd")).parse(dateStr);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return date;
	}	
	
	public static Date strFormatToDate6(String dateStr){
		Date date=null;
		try {
			DateFormat dateTimeformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			date=dateTimeformat.parse(dateStr);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return date;
	}
	/**
	 * <p>time to HH:mm:ss</p>
	 * */	
	public static String timeFormatToStr(Date date){
		return (new SimpleDateFormat("HH:mm:ss")).format(date);
	}
	
	
	/**
	 * 根据年月得到当前月天数
	 * @param dateStr yyyy-MM 
	 * @return
	 */
	@SuppressWarnings("static-access")
	public static int getDaysByDateStr(String dateStr){
		Date date=strFormatToDate4(dateStr);
		Calendar c=Calendar.getInstance();
		c.setTime(date);
		c.set(c.DATE, c.getActualMaximum(Calendar.DATE));
		String lastDate=dateFormatToStr3(c.getTime());
		lastDate=lastDate.substring(8, 10);
		return Integer.parseInt(lastDate);
	}
	
	/**
	 * 获取时间 HH:mm:ss(24小时制)
	 * @param longStr 长整型时间字符串
	 * @return
	 */
	public static String getDateStrByLongStr(String longStr){
		long time=Long.parseLong(longStr);
		String timeStr="";
		if (time>0) {
			Date date=new Date(time);
			timeStr=timeFormatToStr(date);
		}
		return timeStr;
	}
	
	/**
	 * 获取当前month前num个月的列表（yyyyMM）
	 * @param month 年月 yyyyMM
	 * @param num 前num个月数
	 * @return
	 */
	public static List<String> getLastServeralMonthList(String firstMonth,int num){
		List<String> list=new ArrayList<String>();
		for (int i = 0; i < num; i++) {
			Date date=strFormatToDate2(firstMonth);
			Calendar c = Calendar.getInstance();
			c.setTime(date);
			c.add(Calendar.MONTH, -(num-(i+1)));
			list.add(dateFormatToStr2(c.getTime()));
		}
		return list;
	}
 
	
	/**
	 * 验证日期字符串是否合法
	 * @param month yyyyMM
	 * @return true 合法，false 不合法
	 */
	@SuppressWarnings("unused")
	public static boolean isValidDateStr(String month){
		Date date=null;
		boolean result=false;
		try {
			date=(new SimpleDateFormat("yyyyMM")).parse(month);
			result=true;
		} catch (ParseException e) {
			result=false;
		}
		return result;
	}
	
	
	public static List<Date> findDates(Date dBegin, Date dEnd) {  
        List lDate = new ArrayList();  
        lDate.add(dBegin);  
        Calendar calBegin = Calendar.getInstance();  
        // 使用给定的 Date 设置此 Calendar 的时间    
        calBegin.setTime(dBegin);  
        Calendar calEnd = Calendar.getInstance();  
        // 使用给定的 Date 设置此 Calendar 的时间    
        calEnd.setTime(dEnd);  
        // 测试此日期是否在指定日期之后    
        while (dEnd.after(calBegin.getTime())) {  
            // 根据日历的规则，为给定的日历字段添加或减去指定的时间量    
            calBegin.add(Calendar.DAY_OF_MONTH, 1);  
            lDate.add(calBegin.getTime());  
        }  
        return lDate;  
    } 
	/**
	 * 计算参数日期和当前日期相差的天数
	 * @param paraDate yyyy/MM/dd
	 * @return
	 */
	public static int countBalance(String paraDate) {
		//FIXME
		String today = dateFormatToStr3(new Date());
		Date date = strFormatToDate1(paraDate);
		long current = strFormatToDate3(today).getTime();
		long param = date.getTime();
		long banlance = param - current;
		int days = (int) (banlance / (60000 * 60 * 24));
		return days;
	}

	public Calendar getFormatCalendar(String date, String time)
			throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS");
		Date curDate = sdf.parse(date.trim() + " " + time.trim());
		Calendar curCalendar = Calendar.getInstance();
		curCalendar.setTime(curDate);
		return curCalendar;
	}

//	public static void main(String[] args) {
//		DateComm du = new DateComm();
//		try {
//			Calendar calendar = du.getFormatCalendar("2015-07-07", "09:00:00");
//			System.out.println(calendar.getTime());
//		} catch (ParseException e) {
//			e.printStackTrace();
//		}
//	}

}
